
import time, os
from machine import SPI, Pin
import lib.st7735_buf as st7735_buf
from lib.easydisplay import EasyDisplay
from lib.sdcard import SDCard

# 初始化TFT的CS和DC引脚
tft_cs = Pin(5, Pin.OUT)
tft_dc = Pin(4, Pin.OUT)

# 初始化SD卡的CS引脚
sd_cs = Pin(22, Pin.OUT)

# 定义一个函数来切换 SPI 设备
def switch_spi_device(device):
    global spi2
    if device == 'tft':
        spi2=SPI(2, baudrate=40000000, polarity=0, phase=0, sck=Pin(18), mosi=Pin(23))
    elif device == 'sdcard':
        spi2=SPI(2, baudrate=40000000, polarity=0, phase=0, sck=Pin(18), mosi=Pin(23), miso=Pin(19))

# 初始化LCD
def init_lcd():
    switch_spi_device('tft')
    dp = st7735_buf.ST7735(width=160, height=128, spi=spi2, cs=tft_cs, dc=tft_dc, res=19, rotate=1, bl=None, invert=False, rgb=True)
    ed = EasyDisplay(dp, "RGB565", font="/font/text_lite_16px_2312.v3.bmf", show=True, color=0xFFFF, clear=True, auto_wrap=True)
    return ed, dp

# 初始化SD卡
def init_sd():
    global sd
    switch_spi_device('sdcard')
    sd = SDCard(spi2, sd_cs)

# 定义一个函数获取目录中所有BMP文件
def get_bmp_filenames(directory):
    bmp_filenames = []
    # 列出目录中的所有文件和文件夹
    for file in os.listdir(directory):
        # 检查文件扩展名是否为 .bmp
        if file.endswith('.bmp'):
            # 添加文件名到列表
            bmp_filenames.append(file)
    return bmp_filenames

def main():
    # 初始化并获取EasyDisplay和Display对象
    ed, dp = init_lcd()  

    # 读取SD卡的TXT
    init_sd()
    os.mount(sd, '/sd')
    print("SD card mounted")

    # 设置SD卡的挂载点
    sd_mount_point = '/image'

    # 调用函数
    bmp_files = get_bmp_filenames(sd_mount_point)
    print("Found BMP files:", bmp_files)

    for bmp_file in bmp_files:
        # 构建完整的文件路径
        file_path = f'/image/{bmp_file}'
        print(file_path)
        # 调用ed.bmp函数显示图片
        ed.bmp(file_path, 0, 0)
        # 暂停一段时间
        time.sleep(1)

if __name__ == "__main__":
    main()